package com.campusbackend.controller;

import com.campusbackend.entity.Result;
import com.campusbackend.entity.NewsManagement;
import com.campusbackend.service.FileUploadService;
import com.campusbackend.service.NewsManagementService;
import com.campusbackend.utils.ResultUtil;
import com.campusbackend.utils.ThreadLocalUtil;
import com.campusbackend.vo.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理端新闻管理控制器
 *
 * @author yezi
 * @since 2025-07-29
 */
@Slf4j
@RestController
@RequestMapping("/adminUser")
@Tag(name = "管理端新闻管理", description = "管理端新闻相关接口")
public class NewsManagementController {

    @Autowired
    private NewsManagementService newsManagementService;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 获取新闻列表
     * @param page 页码（默认1）
     * @param size 每页数量（默认10）
     * @param status 状态筛选（可选）
     * @return 新闻列表
     */
    @GetMapping("/news")
    @Operation(summary = "获取新闻列表", description = "分页获取新闻列表，支持状态筛选")
    public Result<PageResult<NewsManagementListVO>> getNews(
            @Parameter(description = "页码，默认1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页数量，默认10") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "状态筛选：1-已发布，0-草稿") @RequestParam(required = false) Integer status) {
        
        log.info("获取新闻列表请求 - page: {}, size: {}, status: {}", page, size, status);
        
        try {
            IPage<NewsManagement> pageResult = newsManagementService.getNewsPage(page, size, status);
            
            // 转换为列表VO对象（不包含content字段）
            List<NewsManagementListVO> newsVOs = pageResult.getRecords().stream()
                    .map(news -> {
                        NewsManagementListVO vo = new NewsManagementListVO();
                        BeanUtils.copyProperties(news, vo);
                        return vo;
                    })
                    .collect(Collectors.toList());
            
            PageResult<NewsManagementListVO> result = new PageResult<>(
                    newsVOs,
                    pageResult.getTotal(),
                    pageResult.getCurrent(),
                    pageResult.getSize()
            );
            
            return ResultUtil.success(result);
        } catch (Exception e) {
            log.error("获取新闻列表异常", e);
            return ResultUtil.fail("获取新闻列表时发生错误");
        }
    }

    /**
     * 获取新闻详情
     * @param id 新闻ID
     * @return 新闻详情
     */
    @GetMapping("/news/{id}")
    @Operation(summary = "获取新闻详情", description = "根据ID获取新闻详情")
    public Result<NewsManagementVO> getNewsById(
            @Parameter(description = "新闻ID", required = true) @PathVariable Long id) {
        
        log.info("获取新闻详情请求 - id: {}", id);
        
        try {
            NewsManagement news = newsManagementService.getNewsById(id);
            if (news == null) {
                return ResultUtil.fail("新闻不存在");
            }
            
            // 增加浏览次数
            newsManagementService.incrementViewCount(id);
            
            // 转换为VO对象
            NewsManagementVO vo = new NewsManagementVO();
            BeanUtils.copyProperties(news, vo);
            
            return ResultUtil.success(vo);
        } catch (Exception e) {
            log.error("获取新闻详情异常", e);
            return ResultUtil.fail("获取新闻详情时发生错误");
        }
    }

    /**
     * 发布/创建新闻
     * @param request 新闻请求
     * @return 创建结果
     */
    @PostMapping("/news")
    @Operation(summary = "发布/创建新闻", description = "创建新的新闻")
    public Result<NewsManagementVO> createNews(
            @Valid @RequestBody NewsManagementRequest request) {

        log.info("创建新闻请求 - title: {}, status: {}", request.getTitle(), request.getStatus());

        try {
            // 获取当前登录管理员信息
            Map<String, Object> userInfo = ThreadLocalUtil.get();
            Long publisherId = ((Number) userInfo.get("id")).longValue();

            NewsManagement news = newsManagementService.createNews(
                    request.getTitle(),
                    request.getContent(),
                    request.getSummary(),
                    request.getStatus(),
                    publisherId
            );

            // 转换为VO对象
            NewsManagementVO vo = new NewsManagementVO();
            BeanUtils.copyProperties(news, vo);

            String message = request.getStatus() == 1 ? "新闻发布成功" : "新闻保存成功";
            return ResultUtil.success(vo);
        } catch (Exception e) {
            log.error("创建新闻异常", e);
            return ResultUtil.fail("创建新闻时发生错误");
        }
    }

    /**
     * 更新新闻
     * @param id 新闻ID
     * @param request 更新请求
     * @return 更新结果
     */
    @PutMapping("/news/{id}")
    @Operation(summary = "更新新闻", description = "更新指定ID的新闻")
    public Result<NewsManagementVO> updateNews(
            @Parameter(description = "新闻ID", required = true) @PathVariable Long id,
            @Valid @RequestBody NewsManagementRequest request) {

        log.info("更新新闻请求 - id: {}, title: {}, status: {}", id, request.getTitle(), request.getStatus());

        try {
            NewsManagement news = newsManagementService.updateNews(
                    id,
                    request.getTitle(),
                    request.getContent(),
                    request.getSummary(),
                    request.getStatus()
            );

            // 转换为VO对象
            NewsManagementVO vo = new NewsManagementVO();
            BeanUtils.copyProperties(news, vo);

            return ResultUtil.success(vo);
        } catch (IllegalArgumentException e) {
            log.warn("更新新闻参数错误", e);
            return ResultUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新新闻异常", e);
            return ResultUtil.fail("更新新闻时发生错误");
        }
    }

    /**
     * 删除新闻
     * @param id 新闻ID
     * @return 删除结果
     */
    @DeleteMapping("/news/{id}")
    @Operation(summary = "删除新闻", description = "删除指定ID的新闻（软删除）")
    public Result<String> deleteNews(
            @Parameter(description = "新闻ID", required = true) @PathVariable Long id) {

        log.info("删除新闻请求 - id: {}", id);

        try {
            boolean deleted = newsManagementService.deleteNews(id);
            if (deleted) {
                return ResultUtil.success("新闻删除成功");
            } else {
                return ResultUtil.fail("新闻删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("删除新闻参数错误", e);
            return ResultUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("删除新闻异常", e);
            return ResultUtil.fail("删除新闻时发生错误");
        }
    }

    /**
     * 上传新闻中的图片
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping("/news/upload")
    @Operation(summary = "上传新闻图片", description = "上传新闻富文本内容中的图片文件")
    public Result<Map<String, Object>> uploadNewsImage(@RequestParam("file") MultipartFile file) {
        log.info("收到新闻图片上传请求 - 文件名: {}, 文件大小: {} bytes",
                file.getOriginalFilename(), file.getSize());

        try {
            Map<String, Object> result = fileUploadService.uploadImage(file);

            if ((Boolean) result.get("success")) {
                return ResultUtil.success(result);
            } else {
                return ResultUtil.fail((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("新闻图片上传异常", e);
            return ResultUtil.fail("图片上传时发生错误");
        }
    }
}
